package cn.itcast.service.impl;

import cn.itcast.Dao.RoleDao;
import cn.itcast.Dao.UserDao;
import cn.itcast.domain.Role;
import cn.itcast.domain.User;
import cn.itcast.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author wgq
 * @date 2019-09-20 18:40
 */
@Service
@Transactional(isolation = Isolation.REPEATABLE_READ, readOnly = false, propagation = Propagation.REQUIRED)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Override
    public User login(String username, String password) {
        User user = userDao.findByUsernameAndPassWord(username, password);
        return user;
    }

    @Override
    public List<User> list() {
        List<User> userList = userDao.findAll();
        for (User user : userList) {
            Long id = user.getId();
            List<Role> roles = roleDao.findRoleById(id);
            user.setRoles(roles);
        }
        return userList;
    }

    @Override
    public void save(User user, Long[] roleIds) {
        Long id = userDao.save(user);
        userDao.saveUserRoleRel(id, roleIds);
    }

    @Override
    public void del(Long userId) {
        userDao.delUserRoleRel(userId);
        //int i = 1 / 0;
        userDao.delUser(userId);
    }

    @Override
    public User findOne(Long userId) {
        User user = userDao.findById(userId);
        List<Role> roles = roleDao.findRoleById(userId);
        System.out.println(roles);
        user.setRoles(roles);
        return user;
    }

    @Override
    public void update(User user, Long[] roleIds) {
        userDao.updateUser(user);
        userDao.delUserRoleRel(user.getId());
        userDao.saveUserRoleRel(user.getId(), roleIds);;
    }
}
